<template>
  <div class="container" style="padding:15px">
    <el-card class="box-card">
      <div
        slot="header"
        class="clearfix"
      >
        <span>{{ flag===true?"试题修改":"试题录入" }}</span>
      </div>
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="150px">
        <el-form-item label="学科" prop="subjectID">
          <el-select
            v-model="ruleForm.subjectID"
            placeholder="请选择"
            style="width:480px"
            @change="getList"
          >
            <el-option
              v-for="item in subject"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目录" prop="catalogID">
          <el-select
            v-model="ruleForm.catalogID"
            placeholder="请选择"
            style="width:480px"
          >
            <el-option
              v-for="item in catalogur"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="企业" prop="enterpriseID">
          <el-select v-model="ruleForm.enterpriseID" placeholder="请选择" style="width:480px">
            <el-option
              v-for="item in company"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="province">
          <el-select
            v-model="ruleForm.province"
            placeholder="请选择"
            style="width:233px"
            @change="citychange"
          >
            <el-option
              v-for="item in provinces"
              :key="item"
              :label="item"
              :value="item"
            />

          </el-select>

          <el-select
            v-model="ruleForm.city"
            collapse-tags
            style="margin-left: 14px;width:233px;"
            placeholder="请选择"
          >
            <el-option
              v-for="item in citys"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="方向" prop="direction">
          <el-select v-model="ruleForm.direction" placeholder="请选择" style="width:480px">
            <el-option
              v-for="item in direction1"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <!-- 单选框 -->
        <el-form-item label="题型">
          <el-radio-group v-model="ruleForm.questionType">
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              :label="item.value+''"
            >{{ item.label }}
            </el-radio>

          </el-radio-group>
        </el-form-item>

        <el-form-item label="难度">
          <el-radio-group v-model="ruleForm.difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              :label="item.value+''"
            >{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干" prop="question">
          <Fuwenben2
            v-model="ruleForm.question"
          />

        </el-form-item>

        <el-form-item v-if="ruleForm.questionType=='1'" label="选项">
          <SelectItem v-model="ruleForm.options" :abcd="abcd" />
          <el-row>
            <el-button type="danger" size="small" :disabled="true">+增加选项与答案</el-button>
          </el-row>
        </el-form-item>
        <el-form-item v-if="ruleForm.questionType=='2'" label="选项">
          <CheckboxItem v-model="ruleForm.options" :abcd="abcd" />

          <el-row>
            <el-button type="danger" size="small" @click="addabcd">+增加选项与答案</el-button>
          </el-row>

        </el-form-item>
        <el-form-item v-if="ruleForm.questionType=='3'" />

        <el-form-item label="视频解析" prop="videoURL">
          <el-input v-model="ruleForm.videoURL" style="width:480px" />
        </el-form-item>
        <el-form-item label="答案解析" prop="answer">

          <Fuwenben2
            v-model="ruleForm.answer"
          />
        </el-form-item>
        <el-form-item label="题目备注" prop="remarks">
          <el-input
            v-model="ruleForm.remarks"
            type="textarea"
            style="width:480px;"
            :autosize="{ minRows: 3, maxRows: 8}"
          />

        </el-form-item>
        <el-form-item label="试题标签" prop="tags">
          <el-select
            v-model="tags"
            style="width:480px;"
            multiple
            placeholder="请选择"
          >
            <!-- 线上传来的是字符串，要转为数组 -->
            <el-option
              v-for="(item,index) in ruleForm.tags"
              :key="index"
              :label="item"
              :value="item"
            />

          </el-select>

        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { simple } from '../../api/hmmm/subjects'
import { simple as directoryssimple } from '../../api/hmmm/directorys'// 获取目录
import { list as companylist } from '../../api/hmmm/companys'
import { provinces, citys } from '../../api/hmmm/citys'
import { direction, difficulty, questionType } from '../../api/hmmm/constants'
import Fuwenben2 from '../components/fuwenben2.vue'
import SelectItem from '../components/selectitem.vue'
import CheckboxItem from '../components/checkboxitemm.vue'
import { simple as simplelist } from '../../api/hmmm/tags'
import { add, detail, update } from '../../api/hmmm/questions'

const checkNoticeContent = (rule, value, callback) => {
  if (!value || !value.replaceAll(/<[^>]+>/g, '')) {
    return callback(new Error('内容不能为空'))
  }
  return callback()
}

export default {
  name: 'QuestionNew',
  components: {
    Fuwenben2,
    SelectItem,
    CheckboxItem
  },
  data() {
    return {
      tags: [],
      abcd: ['A', 'B', 'C', 'D'],
      ruleForm: {
        options: [{
          isRight: 0,
          code: null,
          title: '',
          img: ''
        },
        {
          isRight: 0,
          code: null,
          title: '',
          img: ''
        },
        {
          isRight: 0,
          code: null,
          title: '',
          img: ''
        },
        {
          isRight: 0,
          code: null,
          title: '',
          img: ''
        }], // 选框集合
        subjectID: '', // 学科value
        catalogID: '', // 目录value
        enterpriseID: '', // 企业value
        direction: '', // 方向
        province: '', // 城市1 4
        city: '', // 城市2
        question: '', // 题干参数
        answer: '', // 答案解析
        remarks: '',
        tags: [], // 试题标签
        videoURL: '',
        questionType: '1',
        difficulty: '1'
      },
      video: '',
      subject: [],
      catalogur: [], // 目录的数据 // [label:"数据存储"，value:16]
      company: [],
      provinces: [],
      citys: [],
      direction1: [], // 方向
      difficulty: [], // 难度
      questionType: [], // 题型
      simplelist: [],
      id: '',
      rules: {
        subjectID: [
          { required: true, message: '此项目必填', trigger: 'visible-change' }
        ],
        catalogID: [
          { required: true, message: '此项目必填', trigger: 'blur' }
        ],
        enterpriseID: [
          { required: true, message: '此项目必填', trigger: 'blur' }
        ],
        direction: [
          { required: true, message: '此项目必填', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '此项目必填', trigger: 'blur' }
        ],
        question: [
          { validator: checkNoticeContent, message: '此项目必填', trigger: 'blur' },
          { required: true, message: '内容不能为空', trigger: 'blur' }
        ],
        answer: [
          { validator: checkNoticeContent, message: '此项目必填', trigger: 'blur' },
          { required: true, message: '内容不能为空', trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '此项目必填', trigger: 'blur' }
        ],
        videoURL: [
          { required: true, message: '此项目必填', trigger: 'blur' }
        ],
        remarks: [
          { required: true, message: '此项目必填', trigger: 'blur' }
        ]
      },
      flag: false

    }
  },

  watch: {
    'ruleForm.subjectID'(subjectID) {
      // this.ruleForm.catalogID = ''
      this.getList(subjectID)
      // console.log(1)
      // this.ruleForm.catalogID = this.catalogur[0] === undefined ? ' ' : this.catalogur[0].value
    },
    'catalogur'() {
      // console.log(1)
      if (this.catalogur[0] === undefined) {
        this.ruleForm.catalogID = ' '
      } else {
        this.ruleForm.catalogID = this.catalogur[0].value
      }
    }

  },
  created() {
    this.id = this.$route.query.id
    this.simple()
    this.companylist() // 企业名称
    this.provincess()// 城市
    this.direction1 = direction
    this.difficulty = difficulty
    this.questionType = questionType
  },
  mounted() {
    if (this.$route.query.id !== undefined) { // 回填数据
      this.flag = true
      this.detail()
    }
  },
  methods: {
    async detail() { // 回填数据
      const res = await detail({
        id: this.$route.query.id
      })

      this.ruleForm = res.data
      this.ruleForm.tags = this.ruleForm.tags.split(',')

      this.tags = this.ruleForm.tags // 字符串转数组
    },
    async simple() { // 学科
      const { data } = await simple()
      this.subject = data
      // console.log(this.subject)
    },

    async getList(num) { // 目录
      const { data } = await directoryssimple({
        subjectID: num
      })
      this.catalogur = data // [label:"数据存储"，value:16]
      // ruleForm.catalogID 11
      const res = await simplelist({
        subjectID: num
      })
      // if (this.flag === false) { // 这是录入
      const arr = []
      res.data.forEach((item) => {
        arr.push(item.label)
      })
      this.ruleForm.tags = arr// tags
      // console.log(this.ruleForm.tags) // 根据学科选择tags
      // console.log(object);
      // this.tags = this.ruleForm.tags
      // }
      // console.log(this.ruleForm.catalogID)
      // console.log(this.catalogur[0]) // undefined
      // console.log(this.catalogur[0].value)
      // this.ruleForm.catalogID = this.catalogur[0] === undefined ? ' ' : this.catalogur[0].value
      // console.log(1)
    },

    async companylist() {
      const { data: { items }} = await companylist()
      this.company = items
    },
    async provincess() {
      this.provinces = await provinces()
    },
    async citychange(val) {
      this.citys = await citys(val)
      this.ruleForm.city = this.citys[0]
    },
    submitForm() { // 提交表单
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid && this.flag === false) {
          await add({
            ... this.ruleForm,
            tags: this.tags.join() // 数组转为字符串才能传
          })
          this.$message.success('提交成功')
          this.$router.push('/questions/list')
        } else if (valid && this.flag) {
          // console.log(this.ruleForm.catalogID === ' ')
          if (this.ruleForm.catalogID === ' ') {
            this.$message.error('请输入必填项')
          } else {
            await update({
              ...this.ruleForm,
              tags: this.tags.join()
            })
            this.$message.success('修改成功')
            this.$router.push('/questions/list')
          }
        } else {
          this.$message.error('请输入必填项')
          return false
        }
      })
    },
    addabcd() {
      for (let index = 0; index < 1; index++) {
        const letter = String.fromCharCode(this.abcd[this.abcd.length - 1].charCodeAt(0) + 1)
        this.abcd.push(letter)
        this.ruleForm.options.push(
          {
            isRight: 0,
            code: letter,
            title: '',
            img: ''
          }
        )
      }
    }

  }
}
</script>
<style scoped lang="scss">
.box-card {
  .text {
    font-size: 14px;
  }
  .item {
    margin-bottom: 18px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: '';
  }
  .clearfix:after {
    clear: both;
  }
  .box-card {
    width: 480px;
  }
  .video {
    margin: 0;
    padding: 0;
    color: #f56c84!important;
    font-size: 12px;
  }
}
</style>
